﻿using DTCash.Logger;
using DTCash.Logger.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTCash.Redis;
using Uranus.Service.ProductService;
using Uranus.Service.UserService;

namespace Uranus.Service
{
    public class Product : BaseData
    {
        private static Product product = null;

        public Product()
        {

        }

        public static Product GetProduct()
        {
            if (product == null)
            {
                product = new Product();
            }
            return product;
        }

        #region 获取产品列表

        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns> 
        public LoanProductResponse GetLoanProductDTOList(LoanProductRequest request)
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                if (request.LoanProductDto == null)
                {
                    request.LoanProductDto = new LoanProductDTO();
                }
                List<object> keylist = new List<object>();
                if (request.ProductGroupIds != null)
                {
                    keylist.Add(string.Join(",", request.ProductGroupIds));
                }
                if (request.CategoryIds != null)
                {
                    keylist.Add(string.Join(",", request.CategoryIds));
                }
                if (request.ProductStatusIds != null)
                {
                    keylist.Add(string.Join(",", request.ProductStatusIds));
                }
                if (request.LoanPeroidIds != null)
                {
                    keylist.Add(string.Join(",", request.LoanPeroidIds));
                }
                if (request.TrusteeshipStatusIDs != null)
                {
                    keylist.Add(string.Join(",", request.TrusteeshipStatusIDs));
                }
                keylist.Add(request.PageIndex);
                keylist.Add(request.PageSize);

                CacheKey cacheKey = CacheItem.InitByIdentity("GetLoanProductDTOList", keylist.ToArray()).Product.List;
                Func<LoanProductResponse> method = delegate
                {
                    LoanProductResponse res = client.GetLoanProductDTOList(request);
                    return res.Code == 1 ? res : null;
                };
                return base.GetData<LoanProductResponse>(method, cacheKey);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.GetLoanProductDTOList 出现异常", ex.Message.ToString(), request);

                return null;
            }
            finally
            {
                client.Close();
            }
        }

        /// <summary>
        /// 根据产品属性获取产品信息
        /// </summary>
        /// <param name="loanProductRequest"></param>
        /// <returns></returns>
        public LoanProductResponse GetProductByPropertySubId(LoanProductRequest loanProductRequest)
        {
            ProductServiceClient service = new ProductServiceClient();
            try
            {
                List<object> keys = new List<object>();
                keys.Add("GetProductByPropertySubId");
                keys.Add(string.Join(",", loanProductRequest.ProductStatusIds));
                keys.Add(loanProductRequest.PageIndex.ToString());
                keys.Add(loanProductRequest.PageSize.ToString());
                Func<LoanProductResponse> method = delegate
                {
                    LoanProductResponse response = service.GetProductByPropertySubId(loanProductRequest);
                    return response.Code == 1 ? response : null;
                };
                return GetData<LoanProductResponse>(method, CacheItem.InitByIdentity(loanProductRequest.PropertySubId.ToString(), keys.ToArray()).Product.Info);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.GetProductByPropertySubId 出现异常", ex.Message, new
                {
                    PropertySubId = loanProductRequest.PropertySubId,
                    ProductStatusIds = string.Join(",", loanProductRequest.ProductStatusIds),
                    PageIndex = loanProductRequest.PageIndex,
                    PageSize = loanProductRequest.PageSize,
                });
                return new LoanProductResponse();
            }
            finally
            {
                service.Close();
            }
        }

        #endregion

        #region 根据产品编号获取产品信息
        /// <summary>
        /// 获取根据产品编号获取产品属性
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns> 
        public ProductPropertySubDTOResponse GetPropertySubByProductCode(ProductPropertySubDTORequest request)
        {
            ProductService.ProductServiceClient client = new ProductServiceClient();
            try
            {
                CacheKey cacheKey = CacheItem.InitByIdentity(request.LoanProductPropertySubDto.ProductCode, "GetPropertySubByProductCode").Product.PropertyValue;
                Func<ProductPropertySubDTOResponse> method = delegate
                {
                    ProductPropertySubDTOResponse res = client.GetPropertySubByProductCode(request);
                    return res.Code == 1 ? res : new ProductPropertySubDTOResponse();
                };
                return base.GetData<ProductPropertySubDTOResponse>(method, cacheKey);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.GetPropertySubByProductCode 出现异常", ex.Message.ToString(), request.LoanProductPropertySubDto.ProductCode);

                return null;
            }
            finally
            {
                client.Close();
            }
        }

        /// <summary>
        /// 获取根据产品编号获取产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns> 
        public LoanProductResponse GetLoanProductByCode(LoanProductRequest request)
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                CacheKey cacheKey = CacheItem.InitByIdentity(request.LoanProductDto.ProductCode, "GetLoanProductByCode").Product.Info;
                Func<LoanProductResponse> method = delegate
                {
                    LoanProductResponse res = client.GetLoanProductByCode(request);
                    return res.Code == 1 ? res : null;
                };
                return base.GetData<LoanProductResponse>(method, cacheKey);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.GetLoanProductByCode 出现异常", ex.Message.ToString(), request.LoanProductDto.ProductCode);

                return null;
            }
            finally
            {
                client.Close();
            }
        }
        #endregion

        #region 获取产品分组

        /// <summary>
        /// 获取产品分组数据
        /// </summary>
        /// <returns></returns>
        public List<ProductGroupDTO> GetProductGroupDTOList()
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                CacheKey cacheKey = CacheItem.InitByIdentity("GetProductGroupDTOList").Product.List;
                Func<List<ProductGroupDTO>> method = delegate
                {
                    return client.GetProductGroupDTOList();
                };
                return base.GetData<List<ProductGroupDTO>>(method, cacheKey);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.GetProductGroupDTOList 出现异常", ex.Message.ToString());

                return null;
            }
            finally
            {
                client.Close();
            }
        }
        #endregion

        #region 投标验证
        /// <summary>
        /// 检测购买产品是否合格能购买 
        /// </summary>
        /// <param name="inspectionProductRequest"></param>
        /// <param name="loanProductDto">要检测的产品信息</param>
        /// <returns>
        /// Code 1:成功，2：接口查询失败（程序执行出现异常），3：产品不存在，4：产品已满标，5：剩余可投资金额不足 ResiduePrice 为剩余可投金额
        /// 6：未到产品的投标时间，7：购买的产品已过期，8：投资金额不可少于最少投资金额，9：投资金额不可大于最大投资金额，10：不可购买自己的贷款产品
        /// 11： 该产品目前不可进行投资（产品的DisplayStatusID!=1 ）
        /// </returns>
        public InspectionProductResponse InspectionProduct(InspectionProductRequest inspectionProductRequest)
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                return client.InspectionProduct(inspectionProductRequest); ;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "Uranus.Service.Product.InspectionProduct 出现异常", ex.Message.ToString(), inspectionProductRequest);

                return null;
            }
            finally
            {
                client.Close();
            }
        }
        #endregion

        /// <summary>
        /// 获取激活变现卡金额
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="transferPrice"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public decimal GetActivationRedPacketValue(string productCode, decimal transferPrice, int userId)
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                return client.GetActivationRedPacketValue(productCode, transferPrice, userId);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError("Uranus.Service GetActivationRedPacketValue 获取激活变现卡金额 接口异常",
                    string.Format("productCode:{0},transferPrice:{1},userId:{2}", productCode, transferPrice, userId),
                    ex, true);
                return 0;
            }
            finally
            {
                client.Close();
            }
        }

        /// <summary>
        /// 获取数据纰漏信息
        /// </summary>
        /// <returns></returns>
        public DisclosureDTO GetDisclosureDto()
        {
            ProductServiceClient client = new ProductServiceClient();
            try
            {
                return client.GetDisclosureDto();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError("Uranus.Service GetDisclosureDto 获取数据纰漏信息 接口异常", string.Empty, ex, true);
                return null;
            }
            finally
            {
                client.Close();
            }
        }
    }
}
